extends Node

var frame_counter: int = 0


func _ready() -> void:
	DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_ENABLED)
	Engine.max_fps = 120
	RenderingServer.set_default_clear_color(Color.BLACK)
	ResourceManager.preload_resources()


func start_new_game():
	GlobalData.is_new_game = true
	
	GlobalData.player_data = GlobalData.start_player_data.duplicate(true)
	GlobalData.current_level_data = GlobalData.start_level_data.duplicate(true)
	GlobalData.levels_data = []
	GlobalData.levels_data.append(GlobalData.current_level_data)
	
	LevelManager.transition(GlobalData.current_level_data)
	
	
func continue_game():
	GlobalData.is_new_game = false
	
	load_game()
	LevelManager.transition(GlobalData.current_level_data)
	
	
func save_game():
	var level = get_tree().current_scene as Level
	level.collect_data()
	
	var game_save_data = GameSaveData.new()
	game_save_data.player_data = GlobalData.player_data
	game_save_data.current_level_data = GlobalData.current_level_data
	game_save_data.levels_data = GlobalData.levels_data
	game_save_data.window_mode = GlobalData.window_mode
	
	var save_path = "user://game_data.tres"
	var err = ResourceSaver.save(game_save_data, save_path)
	if err != OK:
		push_error("游戏数据保存失败: %s" % err)
	else:
		print("游戏数据保存成功")
		

func has_save_file():
	var save_path = "user://game_data.tres"
	return FileAccess.file_exists(save_path)
		

func load_game():
	var save_path = "user://game_data.tres"
	if FileAccess.file_exists(save_path):
		var game_data: GameSaveData = load(save_path)
		
		GlobalData.player_data = game_data.player_data
		GlobalData.current_level_data = game_data.current_level_data
		GlobalData.levels_data = game_data.levels_data
		GlobalData.window_mode = game_data.window_mode
		
		print("游戏数据加载成功, ", game_data)
	else:
		print("游戏数据加载失败，不存在文件")
		

func _process(delta: float) -> void:
	frame_counter += 1
		

func delete_save_file() -> void:
	var save_path = "user://game_data.tres"
	if FileAccess.file_exists(save_path):
		var err = DirAccess.remove_absolute(ProjectSettings.globalize_path(save_path))
		if err == OK:
			print("存档文件已成功删除")
		else:
			push_error("删除存档失败，错误码: %s" % err)
	else:
		print("未找到存档文件，无需删除")

	
